﻿using System.Linq;
using System.Text;
using System.Web.Mvc;
using Enyim.Caching;
using SilenthinkCommon.Extension;
using SilenthinkContract;
using SilenthinkContract.Component;
using Web.Areas.Item.Models;
using SilenthinkContract.Domain;
using System.Collections.Generic;
using Web.Controllers;

namespace Web.Areas.Item.Controllers
{
    public class HomeController : BaseController
    {
        public HomeController(ILogService logService, IBaseService baseService, IExtraService extraService, IStoreService storeService, IOrderService orderService, IGameService gameService, IAuctionService auctionService, IPassportService passportService, IPaymentService paymentService, IMemcachedClient memcachedClient) : base(logService, baseService, extraService, storeService, orderService, gameService, auctionService, passportService, paymentService, memcachedClient)
        {
        }

        /// <summary>
        /// 产品
        /// </summary>
        /// <param name="param">产品Id</param>
        /// <returns></returns>
        //[Static(10)]
        public ActionResult Index(long param = 0)
        {
            var model = new HomeControllerModel.Index();
            var product = StoreService.GetProduct(param, true, true);
            var defaultVariant = product.ProductVariants.OrderBy(o => o.VariantPrice).First();
            var categories = MemcachedClient.Put(CacheKey.Store.ProductCategory, () => StoreService.GetProductCategories().ToList());

            model.Product = product;
            //model.DefaultVariant = defaultVariant;
            model.Attributes = GetVariantAttributes(product);
            model.SelectedAttributes = defaultVariant.VariantCode.Split(',');
            var code = product.CategoryCode.Substring(0, product.CategoryCode.Length - 2);
            model.ProductCategories = categories.Where(o => o.Code == code).ToList();
            return View(model);
        }

        public ActionResult Js(long param)
        {
            var product = StoreService.GetProduct(param, false, true);
            if (product != null)
            {
                var sb = new StringBuilder();
                sb.Append(GetProductInfo(product));
                return JavaScript(sb.ToString());
            }
            return null;
        }

        /// <summary>
        /// 咨询
        /// </summary>
        /// <param name="param">产品Id</param>
        /// <param name="category">咨询分类</param>
        /// <param name="page">索引页</param>
        /// <param name="size">分页大小</param>
        /// <returns></returns>
        public ActionResult Advisory(long param, ProductAdvisoryCategory? category = null, int page = 1, int size = 20)
        {
            var model = StoreService.GetPagedProductAdvisory(page, size, param, category: category).ToPagedList(page, size);
            return PartialView(model);
        }

        /// <summary>
        /// 评论
        /// </summary>
        /// <param name="param">产品Id</param>
        /// <param name="status">评论状态</param>
        /// <param name="page">索引页</param>
        /// <param name="size">分页大小</param>
        /// <returns></returns>
        public ActionResult Review(long param, ProductReviewStatus? status = null, int page = 1, int size = 20)
        {
            var model = StoreService.GetPagedProductReview(page, size, param, status: status).ToPagedList(page, size);
            return PartialView(model);
        }

        private static string GetProductInfo(Product product)
        {
            var sb = new StringBuilder();
            sb.Append("var itemInfo={");
            if (product != null)
            {
                var variants = product.ProductVariants.ToArray();
                var stock = variants.Sum(o => o.VariantQuantity);
                sb.AppendFormat("'Id':{0},'Name':'{1}','Price':{2},'Stock':{3},'Dimension':{4},'Variants':{5},'VariantAttributes':{6}", product.Id, product.Name, product.UnitPrice, stock, (byte)product.Dimension, GetVariants(variants), GetStringVariantAttributes(product));
            }
            sb.Append("}");
            return sb.ToString();
        }
        private static IDictionary<string, IList<string>> GetVariantAttributes(Product product)
        {
            var dic = new Dictionary<string, IList<string>>();
            var list = new List<KeyValuePair<string, string>>();

            if (product.Dimension == ProductDimension.Two)
            {
                var variants = product.ProductVariants.ToArray();
                list.AddRange(variants.Select(variant => variant.VariantCode.Split(',')).Select(temp => new KeyValuePair<string, string>(temp[0], temp[1])));
            }
            var main = list.GroupBy(o => o.Key).Select(o => o.Key);
            foreach (var s in main)
            {
                var temp = s;
                var sub = list.Where(o => o.Key == temp).Select(o => o.Value).ToList();
                dic.Add(s, sub);
            }
            var mainBate = list.GroupBy(o => o.Value).Select(o => o.Key);
            foreach (var s in mainBate)
            {
                var temp = s;
                var sub = list.Where(o => o.Value == temp).Select(o => o.Key).ToList();
                dic.Add(s, sub);
            }
            return dic;
        }
        private static string GetStringVariantAttributes(Product product)
        {
            var dic = GetVariantAttributes(product);
            var sb = new StringBuilder();
            sb.Append("{");
            var i = 0;
            foreach (var d in dic)
            {
                var s = d.Value.Aggregate(string.Empty, (current, o) => current + ("'" + o + "',")).Trim(',');
                sb.AppendFormat(i == dic.Count - 1 ? "'{0}':[{1}]" : "'{0}':[{1}],", d.Key, s);
                i++;
            }
            sb.Append("}");
            return sb.ToString();
        }
        //private static string GetVariantAttributes(IList<ProductVariant> variants)
        //{
        //    var sb = new StringBuilder();
        //    sb.Append("[");
        //    for (var i = 0; i < variants.Count; i++)
        //    {
        //        var variant = variants[i];

        //        if (i < variants.Count - 1)
        //        {
        //            sb.AppendFormat("[{0}],", variant.VariantCode);
        //        }
        //        else
        //        {
        //            sb.AppendFormat("[{0}]", variant.VariantCode);
        //        }
        //    }
        //    sb.Append("]");
        //    return sb.ToString();
        //}

        private static string GetVariants(IList<ProductVariant> variants)
        {
            var sb = new StringBuilder();
            sb.Append("[");
            for (var i = 0; i < variants.Count; i++)
            {
                var variant = variants[i];

                if (i < variants.Count - 1)
                {
                    sb.AppendFormat("{{'Id':'{0}','Price':{1},'Quantity':{2},Code:'{3}'}},", variant.Id, variant.VariantPrice, variant.VariantQuantity, variant.VariantCode);
                }
                else
                {
                    sb.AppendFormat("{{'Id':'{0}','Price':{1},'Quantity':{2},Code:'{3}'}}", variant.Id, variant.VariantPrice, variant.VariantQuantity, variant.VariantCode);
                }
            }
            sb.Append("]");
            return sb.ToString();
        }
    }
}
